//删除上传图片文件
function deleteCostUploadImage(){
    var filePath = "/temp/"+$("#costImagePathId").val();
    if (filePath){
        var result = commonAjax("post","/costReport/deleteCostReportUploadFile",{filePath:filePath});
        if (result.status==200){
            $("#costImagePathId").val("")    //把值设置为""
            $("#costReportFormImage").attr("src","")
            $("#costReportFormImageDiv").hide() // 隐藏图片
            $("#costImagePathDiv").show();
            $("#costUploadTuPian").html("<i class=\"fa fa-plus-square fa-fw\"></i>添加")
        }
    }

}

//第二个物料编码
var finishedProductCode2Geshi=true;
$("#finishedProductCode2").textbox({
    prompt:'格式：编码1,编码2~编码4,编码5',
    onChange:function (newValue,oldValue) {
        var s1=newValue.lastIndexOf('，') //中文逗号
        if (s1!=-1){
            finishedProductCode2Geshi=false;
            $.messager.alert('分隔符错误','有【中文逗号】分隔符，要求【英文逗号】','error');
            return
        }
        finishedProductCode2Geshi=true;
    }
})

//点击事件，
$("#costUploadTuPian").click(function () {
    //触发点击事件，input标签file类型的点击事件
    $("#costReportFormFile").click();
})

function costReportUploadFile(urlPath) {
    //先进行尝试删除文件上的服务器，更换图片会造成多余的图片
    var filePath = $("#costImagePathId").val();
    if (filePath){
        commonAjax("post","/costReport/deleteCostReportUploadFile",{filePath:filePath});
    }
    var myform = new FormData();
    myform.append('file', $("#costReportFormFile")[0].files[0]);

    $.ajax({
        url: "/costReport/costReportUploadFile",
        type: "POST",
        data: myform,
        async: false,
        contentType: false,
        processData: false,
        success: function (result) {
            if (result.status==200){
                $("#costReportFormImageDiv").show();
                //$("#costReportFormImage").show()
                $("#costReportFormImage").attr("src","/temp/"+result.msg)
                $("#costImagePathDiv").hide();
                $("#costUploadTuPian").html("<i class=\"fa fa-reply-all fa-fw\"></i>更换")
                //赋值图片路径值
                $("#costImagePathId").val(result.msg)
            }
        },

    });

}

//成品编码只输入一个的方式事件
$("#finishedProductCode").textbox({
    onChange: function (newValue, oldValue) {
        //刷出成品编码的规格，单位等和此成品编码的配件信息
        brushOutTheFinishedCodeAccessories(newValue);
    }

})

//刷出成品编码配件方法实现
function brushOutTheFinishedCodeAccessories(newValue) {
    if(costReportUpdateAndCoopyC){//拷贝、修改，第一次打开不进行触发此事件
        if (newValue) {
            var pkOrg = costReportFormPkOrgAccount.combobox("getValue");
            $.ajax({
                url: '/costReportForm/selectCostCodingItem?costCoding=' + newValue + '&pkOrg=' + pkOrg,
                success: function (data) {
                    if (data.status == 200 || data.status == 201) {
                        $("#productName").textbox("setValue", data.obj.property.REMARK2);//品名
                        $("#costReport_Form_capacity").textbox("setValue", data.obj.property.REMARK3);//规格
                        $("#costReport_Form_costReportUnits").textbox("setValue", data.obj.property.REMARK4);//单位
                        //往 C配件插入数据
                        if (data.status == 200) { //证明找到全部数据
                            $.messager.confirm('确认','从系统中有查询到此成品编码的相关配件信息，是否需要更新插入？',function(r){
                                if (r){
                                    emptyMountings();//先进行判断是否清空数据
                                    var parts = data.obj.parts;
                                    for (var i = 0; parts.length > i; i++) {
                                        costReportC.edatagrid('addRow', {
                                            //配件
                                            row: {
                                                coding:parts[i].CODE,
                                                mountings: parts[i].NAME,
                                                mountingsPrice: parts[i].NGTAXPRICE == undefined ? 0 : parts[i].NGTAXPRICE,
                                                mountingsRemark:parts[i].KL,
                                            }
                                        })
                                    }
                                }
                                costReportC.edatagrid('saveRow')
                                costReportC.edatagrid('clearSelections');  //清除选中的行
                            });

                        }
                    } else {
                        $("#productName").textbox("setValue", "");//品名
                        $("#costReport_Form_capacity").textbox("setValue", "");//规格
                        $("#costReport_Form_costReportUnits").textbox("setValue", "");//单位
                        layer.msg("没有找到这个物料编号!请检查是否填写正确!")
                    }
                },
                error: function (data) {
                    alert("系统维护中！");
                }
            })
        }
    }else {
        //处理修改拷贝第一次进来不进行刷新
        costReportUpdateAndCoopyC=true;
    }
}

//客户编码
$("#clientcode").textbox({
    onChange: function () {
        var clientcode = $("#clientcode").val();
        if (clientcode != '') {
            $.post({
                url: '/costReportForm/getbdCustomerName?code=' + clientcode,
                success: function (data) {
                    if (data == null || data == '') {
                        layer.msg("没有找到这个客户编码!请检查是否填写正确!")
                    } else {
                        $("#clientName").textbox('setValue', data);
                    }
                }
            })
        }
    }
})


//---------------------------------------------------------------------水料价中的计算 start---------------------------------------------------
//实际灌装重量手动修改后触发事件
function costReportaActualValueOnChange(newValue,oldValue) {
    if (newValue) {
        var editors = costReportA.datagrid('getEditors', getRowIndex(this));
        var priceEditorVal = editors[5].target.val();      //实际罐装重量对象
        var costEditor = editors[7];        //成本价对象
        var cost = newValue * priceEditorVal;
        $(costEditor.target).numberbox('setValue', fomatFloat(cost,4));

        //报价率：
        var quotedPriceVal = 2; //默认5元以下1千克*2
        if (priceEditorVal >= 5 && priceEditorVal < 10) {
            quotedPriceVal = 1.75;
        } else if (priceEditorVal >= 10) {
            quotedPriceVal = 1.5
        }
        var quotedPrice = editors[8];
        $(quotedPrice.target).numberbox('setValue', quotedPriceVal);
    }
}

//实际灌装重量：标准容量*比重率=实际灌装重量
function setEditing_actual_value(rowIndex) {
    //cost_report_a :datagrid的id
    var editors = costReportA.datagrid('getEditors', getRowIndex(rowIndex));
    var priceEditor = editors[0];       //新增一行：标签容量对象
    var amountEditor = editors[1];      //比重率
    var costEditor = editors[2];        //实际罐装重量
    var cost = priceEditor.target.val() * amountEditor.target.val();
    //大于0：配方号才可以输入
    if (cost > 0) {
        var priceEditor3 = editors[4];
        $(priceEditor3.target).numberbox('readonly', false);
    }
    $(costEditor.target).numberbox('setValue', cost.toFixed(6));
};

//配方号触发事件
function detailNameOnChange(newValue, oldValue) {
    var editors = costReportA.datagrid('getEditors', getRowIndex(this));
    if (newValue) {   //判断不能为空、Undefined
        var data = commonAjax("post", "/costReportForm/selectArticlePrice", {"peiFangHao": newValue})
        if (data.status != 200) {
            layer.msg(data.msg)
        } else {
            var articlePrice = data.obj;
            var priceEditor = editors[6];
            //系统获取水料单价
            $(priceEditor.target).numberbox('setValue',articlePrice)
        }
    }
}

//报价率：根据水料单价【￥5/kg以下X2】【￥5/kg-￥10/kgX1.75】【￥10/kg-￥20/kgX1.5】如少有/全新的配方或开料复杂要先咨询开发部才定
//成本价：实际罐装重量*水料单价=成本价
function setEditing_cost_price(priceEditorVal,oldValue) {//水料单价值
    var rowIndex=this;
    var editors = costReportA.datagrid('getEditors', getRowIndex(rowIndex));
    var priceEditor1 = editors[2];      //实际罐装重量对象
    var costEditor = editors[7];        //成本价对象
    var cost = priceEditorVal * priceEditor1.target.val();
    $(costEditor.target).numberbox('setValue', (cost + 0.0001).toFixed(3));

    //报价率：
    var quotedPriceVal = 2; //默认5元以下1千克*2
    if (priceEditorVal >= 5 && priceEditorVal < 10) {
        quotedPriceVal = 1.75;
    } else if (priceEditorVal >= 10) {
        quotedPriceVal = 1.5
    }
    var quotedPrice = editors[8];
    $(quotedPrice.target).numberbox('setValue', quotedPriceVal);

    costReportA.edatagrid("saveRow");
};

//---------------------------------------------------------------------B 人工、其它费用 start-----------------------------------------------------

//1、按钮【标准工时详情】触发方法
function formatCountItem() {
    //打开可选择类型
    $('#InitialInfo_crii_type').combobox('enable');
    initialInfoDlg.init2()
    //保存下计算单支工时的表
    $('#InitialInfo_table').edatagrid('saveRow');
    $('#InitialInfo_dlg').dialog('center') //纠正窗口
}

//2、按钮【添加】:弹出窗口
function formatCount() {
    //打开可选择类型
    $('#InitialInfo_crii_type').combobox('enable');
    initialInfoDlg.init()
    $('#InitialInfo_dlg').dialog('center') //纠正窗口
}

//InitialInfo_crii_typed的combobox类型的onChange事件方法
function setEditing_worker_type(newValue,oldValue) {
    var thisNewValue=newValue;
    if (newValue == 4) {
        newValue = 3;
    }
    // 初始化类型表格：InitialInfo_table2
    initialInfoDataTable.init(newValue,thisNewValue)
    //计算单支工时表格进行类型初始化表格
    if (newValue == 1) {
        initialInfoTable.it();
    } else {
        initialInfoTable.it2();
    }
}

//B人工-人工类型工时-组织触发事件
function initialInfoCriiPkOrgOnChange(newValue,oldValue){
    var type=$('#InitialInfo_crii_type').combobox('getValue');
    var data={"type": type,"pkOrg":newValue}
    var data = commonAjax("get", "/costReportForm/costReportInitialInfo", data)
    $('#InitialInfo_table2').datagrid("loadData", data);
}

function InitialInfo_doSearch(value,name){
    //alert('You input: ' + value+'('+name+')');
    var pkOrg=$("#InitialInfo_crii_pkOrg").combobox("getValue");
    var type=$('#InitialInfo_crii_type').combobox('getValue');
    var data;
    if (pkOrg){
        data={"type": type,"pkOrg":pkOrg}
    }else{
        data={"type": type}
    }

    data[name]=value

    var data = commonAjax("get", "/costReportForm/costReportInitialInfo", data)
    $('#InitialInfo_table2').datagrid("loadData", data);
}

// 灌装总量的计算
function initialInfoTableImOnChange(initialInfo_milliliter,oldValue) {
    var editors = $('#InitialInfo_table').datagrid('getEditors', getRowIndex(this));
    var standard_date=  editors[4].target.val()         //标准工时
    var appendManHour=  editors[5].target.val()         //附加工时
    var singlehours=    editors[7].target;              //单支工时
    var pkOrg= editors[8].target.val();                 //组织
    if(pkOrg=="0001O110000000001HET"){
        singlehours.numberbox('setValue',Number(initialInfo_milliliter)*(Number(appendManHour)+Number(standard_date))/1000);
    }else {
        singlehours.numberbox('setValue',Number(initialInfo_milliliter)*(Number(appendManHour)+Number(standard_date))/60);
    }
}

//附加工时计算
function appendManHourOnChange(newValue,oldValue) {
    var rowIndex=this;
    var editors = $('#InitialInfo_table').datagrid('getEditors', getRowIndex(rowIndex));
    var workerType= editors[2].target.val()    //类型
    var standard_date= editors[4].target.val()  //标准工时
    var singlehours;   //单支工时
    var pkOrg;
    if(workerType=='1'){
        pkOrg= editors[8].target.val();   //组织
        var initialInfo_milliliter=editors[6].target.val() //灌装重量
        singlehours= editors[7].target;   //单支工时
        if(pkOrg=="0001O110000000001HET"){
            singlehours.numberbox('setValue',Number(initialInfo_milliliter)*(Number(newValue)+Number(standard_date))/1000);
        }else {
            singlehours.numberbox('setValue',Number(initialInfo_milliliter)*(Number(newValue)+Number(standard_date))/60);
        }

    }else {
        pkOrg= editors[7].target.val();   //组织
        singlehours= editors[6].target;   //单支工时
        if(pkOrg=="0001O110000000001HET") {
            singlehours.numberbox('setValue', (Number(newValue) + Number(standard_date)) / 10000);
        }else {
            singlehours.numberbox('setValue', (Number(newValue) + Number(standard_date)) / 60);
        }
    }
}

//销毁事件没有效果啊不知道怎么回事。。。
function InitialInfo_tableDestroy() {
    $('#InitialInfo_table').edatagrid('destroyRow');
    var itNum = $('#InitialInfo_table').datagrid("getRows");

    if (itNum.length - 1 <= 0) {
        $('#InitialInfo_crii_type').combobox('enable'); //启用
    } else {
        $('#InitialInfo_crii_type').combobox('disable'); //禁用
    }

}

//清空
function InitialInfoTableEmpty() {
    var itNum = $('#InitialInfo_table').datagrid("getRows");
    if (itNum.length > 0){
        $('#InitialInfo_table').datagrid('loadData',{total: 0, rows: []})
        $('#InitialInfo_crii_type').combobox('enable'); //启用
    }

}

//保存弹窗赋值单支工时
function save_InitialInfo() {
    //获取类型
    var type= $('#InitialInfo_crii_type').combobox('getValue');
    //进行保存操作
    $('#InitialInfo_table').edatagrid('saveRow');
    var rows2 = $('#InitialInfo_table').datagrid('getRows');
    //往全局变量中赋值
    var rows=[];
    rows2.forEach(function (val) {
        val.costId=Date.parse(new Date())
        val.workerType=type;    //由于4的类型都在3中，只能这样操作
        rows.push(val);
        costReportBSinglehoursItem.push(val);
    })

    if (rows.length > 0) {
        var priceHours = commonAjax("post", "/costReportForm/getPriceHours");           //获取工时单价

        if (type==1 ||type==2 || type==4) {//配置人工，罐装基础人工，搬运人工是累加
            var standardDate = 0;               //最终标准工时
            var standardType='';
            var cost_report_singlehour = 0;     //最终单支工时
            for (var i = 0; i < rows.length; i++) {

                //标准工时:需要处理附加工时和标准工时相加
                var appendManHour=Number(rows[i].appendManHour);//附加工时
                var standard = fomatFloat(Number(rows[i].standard_date),3);//标准工时
                standard=appendManHour+standard;   //附加工时+标准工时
                //单支工时
                var singlehour = parseFloat(rows[i].singlehours)

                //配置人工特殊处理
                if(type==1){
                    //标准工时：只取最大值
                    if(standard>standardDate){
                        standardDate=standard;
                    }
                    //单支工时：只取最大值
                    if(singlehour>cost_report_singlehour){
                        cost_report_singlehour=singlehour;
                    }
                }else {
                    standardDate+= standard;
                    cost_report_singlehour = cost_report_singlehour + singlehour;
                }

                //工艺标准(其实就是名称了)
                standardType+=rows[i].standard_type+",";

            }
            standardType= standardType.substring(0,standardType.length-1);

            switch (type) {
                case '1':
                    //配置人工
                    costReportB.edatagrid('addRow', {
                        index: 0,
                        row: {
                            subId: rows[0].subId,                                   //产品标准工时的主键id：用于判断是否能删除或修改
                            costId:rows[0].costId,                                  //此字段用于关联获取操作单支工时的详情 生成的时间轴
                            workerType: 1,
                            pieceTime: cost_report_singlehour,                      //赋值单支工时
                            standardTime: standardDate,                             //赋值标准工时
                            timeUnitPrice: priceHours,                              //赋值工时单价
                            price: (cost_report_singlehour * priceHours).toFixed(4),              //价格/pcs
                            processDecomposition: standardType                      //工艺分解
                        }
                    });
                    break;
                case '2':
                    //罐装基础人工赋值单支工时
                    costReportB.edatagrid('addRow', {
                        index:1,
                        row: {
                            subId: rows[0].subId,                                   //产品标准工时的主键id：用于判断是否能删除或修改
                            costId:rows[0].costId,                                  //此字段用于关联获取操作单支工时的详情 生成的时间轴
                            workerType: 2,//rows[i].workerType,
                            pieceTime: fomatFloat(cost_report_singlehour,4),                         //赋值单支工时
                            standardTime: fomatFloat(standardDate,3),                    //赋值标准工时
                            timeUnitPrice: priceHours,                              //赋值工时单价
                            price: fomatFloat((cost_report_singlehour * priceHours),4),                //价格/pcs
                            processDecomposition: standardType                      //工艺分解(待处理数组)
                        }
                    });
                    break;
                case '4':
                    //搬运工赋值单支工时
                    costReportB.edatagrid('addRow', {
                        row: {
                            subId: rows[0].subId,                                   //产品标准工时的主键id：用于判断是否能删除或修改
                            costId:rows[0].costId,                                          //此字段用于关联获取操作单支工时的详情，生成的时间轴
                            workerType: 4,//rows[i].workerType,
                            pieceTime: fomatFloat(cost_report_singlehour,4),
                            standardTime: fomatFloat(standardDate,3),
                            timeUnitPrice: priceHours,
                            price: fomatFloat((cost_report_singlehour * priceHours),4),
                            processDecomposition: standardType
                        }
                    });
                    break;
            }

        } else {
            //罐装/组装人工
            for (var i = 0; rows.length > i; i++) {

                costReportB.edatagrid('addRow', {
                    index:2,
                    row: {
                        subId: rows[i].subId,                                   //产品标准工时的主键id：用于判断是否能删除或修改
                        costId:rows[i].costId,                                          //此字段用于关联获取操作单支工时的详情
                        workerType: 3,//rows[i].workerType,
                        pieceTime: fomatFloat(rows[i].singlehours,4),
                        standardTime: fomatFloat(Number(rows[i].standard_date)+Number(rows[i].appendManHour),3),
                        timeUnitPrice: priceHours,
                        price: fomatFloat((rows[i].singlehours * priceHours),4),
                        processDecomposition: rows[i].standard_type
                    }
                });
            }

        }

        costReportB.edatagrid('saveRow');
        cost_report_b_count(); //统计B的方法
        final_result();         //统计总成本的方法
        $('#InitialInfo_dlg').dialog('close');
        $('#InitialInfo_table').datagrid("loadData", {total: 0, rows: []});             //清空datagrid
        $('#InitialInfo_table2').datagrid("loadData", {total: 0, rows: []});             //清空datagrid
        $("#InitialInfo_crii").textbox("setValue", "");                                  //清空模糊查询

    } else {
        layer.msg("你还没有添加内容！")
    }
}

//第一次打开修改页面：总成本计算不正确问题
function oneUpdateShow(val) {
    $("#v_a_t_export_tax_rate").numberbox('setValue', 1);
    $("#v_a_t_export_tax_rate").numberbox('setValue', val);
}

//提示有没有安装锐浪web客户端程序
// $(function () {
//     webapp_ws_autoupdate();
// })

//锐浪报表easyui弹窗方式显示
function ruilangFromEasyUiOption() {
    //grf模板
    var costReport_grfURL = "/grf/chengben.grf";
    var costReport_Json;
    $('#costReport_Table').dialog('open').dialog('setTitle', '成本报告表');
    $("#costReport_noPass").hide();
    $("#costReport_Table_print").hide();
    $("#costReport_check").hide();
    var costReport_Table;
    //创建报表显示器，参数指定其在网页中的占位标签的ID，
    costReport_Table = window.rubylong.grhtml5.insertReportViewer('costReport_Table', urlAddRandomNo(costReport_grfURL));
    costReport_Table.stop();
    costReport_Table.dataPrepared = false;
    //console.log("343435",msg);
    costReport_Json = msg;
    costReport_Table.loadData(msg);
    costReport_Table.start();
    if (msg.table[0].costReportStatus == 0) {
        $("#costReport_check").show();
    } else if (msg.table[0].costReportStatus == 2) {
        $("#costReport_noPass").show();
    } else {
        $("#costReport_Table_print").show();
    }
}

//B 其它费用 ---------------------------------------------------start---------------------------------------------------------------------------
function calculateOnUpdate(content) {
    content.panel({
        width: 380,
        border: false,
        href:'/costReportForm/otherCost/'+this.getAttribute('pagehtml'),
        onLoad:function () {
            //弹出窗迷你小窗为订单量赋值(只加载一次)
            var b=Number($("#orderQuantityId").numberbox('getValue'));
            $("#fumigationChargeCostId1").numberbox("setValue",b);
            $("#cartonCeartIficateCostId1").numberbox("setValue",b);
            $("#customsFeeCostId1").numberbox("setValue",b);
        }
    });
}

//订单量值改变事件
function  orderQuantityIdOnChange(newValue,oldValue){
    //为其它费用: 实报实销中的计算公式赋值，未触发迷你小窗口是无法赋值的
    $("#cartonCeartIficateCostId1").numberbox("setValue",newValue);
    $("#fumigationChargeCostId1").numberbox("setValue",newValue);
    $("#customsFeeCostId1").numberbox("setValue",newValue);
}


function calculateOnShow() {
    //设置装箱数量
    $("#freightPackingQuantity").numberbox("setValue",$("#costReport_Form_encasementQuantity").textbox("getValue"))
    //设置运费的长宽高
    if (cartonTableData.length>0){
        $("#freightWeight1").numberbox("setValue",cartonTableData[0].len)
        $("#freightWidth").numberbox("setValue",cartonTableData[0].w)
        $("#freightHeight").numberbox("setValue",cartonTableData[0].h)
    }else{
        $("#freightWeight1").numberbox("setValue",0)
        $("#freightWidth").numberbox("setValue",0)
        $("#freightHeight").numberbox("setValue",0)
    }
    var t = $(this);
    t.tooltip('tip').unbind().bind('mouseenter', function(){
        t.tooltip('show');
    }).bind('mouseleave', function(){
        t.tooltip('hide');
    });
}

$("#calculateFumigationCharge").tooltip({
    content: $('<div id="calculateFumigationChargeDiv"></div>'),
    showEvent: 'mouseover',
    onUpdate: calculateOnUpdate,
    onShow: calculateOnShow
});
$("#calculateCartonCertificate").tooltip({
    content: $('<div id="calculateCartonCertificateDiv"></div>'),
    showEvent: 'mouseover',
    onUpdate: calculateOnUpdate,
    onShow: calculateOnShow
});
$("#calculateFreight").tooltip({
    content: $('<div id="calculateFreightDiv"></div>'),
    showEvent: 'mouseover',
    onUpdate: calculateOnUpdate,
    onShow: calculateOnShow
});

$("#calculateCustoms_fee").tooltip({
    content: $('<div id="calculateCustoms_feeDiv"></div>'),
    showEvent: 'mouseover',
    onUpdate: calculateOnUpdate,
    onShow: calculateOnShow
});

$("#calculateOtherCharges").tooltip({
    content: $('<div id="calculateOtherChargesDiv"></div>'),
    showEvent: 'mouseover',
    onUpdate: calculateOnUpdate,
    onShow: calculateOnShow
});

$('#fumigation_charge').numberbox({
    onChange: function () {
        other_expenses_count();
    }
});
$('#carton_certificate').numberbox({
    onChange: function () {
        other_expenses_count();
    }
});

//点击【授权费\顾问\其他】触发方法
function calculateOtherChargesZtOnClick(){
    //根据自身找父类元素，然后添加html内容
    $("#calculateOtherCharges").parent().append("<div id='calculateOtherChargesZtDialog'><table id='calculateOtherChargesZtTable'></table></div>")
    $("#calculateOtherChargesZtDialog").dialog({
        title:"费用详情",
        width:600,
        height:300,
        modal:true,
        onOpen:function () {
            //初始化表格
            $("#calculateOtherChargesZtTable").edatagrid({
                url:'/costReportForm/getCalculateOtherChargesZtTableData',
                singleSelect:false,
                queryParams:{costReportId:$("#costReportId").textbox("getValue")},
                columns:[[
                    {field:'otherChargesName',title:'费用名称',width:186,align:'center',editor:{type:'text'}},
                    {field:'otherChargesMoney',title:'金额',width:78,align:'center',editor:{type:'numberbox',options:{precision:4,onChange:calculateOtherChargesZtTableonChange}}},
                    {field:'otherChargesNum',title:'数量',width:68,align:'center',editor:{type:'numberbox',options:{precision:4,onChange:calculateOtherChargesZtTableonChange}}},
                    {field:'otherChargesPrice',title:'单价',width:78,align:'center',editor:{precision:4,type:'numberbox',options:{precision:4}}},
                    {field:'otherChargesRemark',title:'备注',width:171,align:'center',editor:{type:'text'}}
                ]],
                toolbar: [{
                    iconCls: 'icon-add',
                    handler: function(){
                        //获取订单数量赋值到数量中
                        var orderQuantityId= $("#orderQuantityId").numberbox("getValue");
                        $("#calculateOtherChargesZtTable").edatagrid("addRow",{
                            row:{
                                otherChargesNum:orderQuantityId
                            }

                        })
                        //清除选中
                        $("#calculateOtherChargesZtTable").edatagrid("clearSelections")
                    }
                },'-',{
                    iconCls: 'icon-remove',
                    handler: function(){
                        $("#calculateOtherChargesZtTable").edatagrid("destroyRow")
                    }
                },'-',{
                    iconCls: 'icon-save',
                    handler: function(){
                        $("#calculateOtherChargesZtTable").edatagrid("saveRow")
                    }
                }
                ],
                onSave:function (index,row) {
                    //用于清除双击后点另一个会自动保存上一个行然后是默认选中
                    $("#calculateOtherChargesZtTable").edatagrid("clearSelections")
                },
                onLoadSuccess:function (data) {//数据加载成功后触发
                    console.log(data)
                    if (data.rows.length<=0){
                        //$("#calculateOtherChargesZtTable").edatagrid("loadData",calculateOtherChargesZtTableData)
                        calculateOtherChargesZtTableData.forEach(function (val) {
                            $("#calculateOtherChargesZtTable").edatagrid("addRow",{
                                row:{
                                    otherChargesName:val.otherChargesName,
                                    otherChargesMoney:val.otherChargesMoney,
                                    otherChargesNum:val.otherChargesNum,
                                    otherChargesPrice:val.otherChargesPrice,
                                    otherChargesRemark:val.otherChargesRemark
                                }

                            })
                        })
                        $("#calculateOtherChargesZtTable").edatagrid("saveRow")
                    }
                }
            })
        },
        buttons:[{
            text:'保存',
            handler:function(){
                $("#calculateOtherChargesZtTable").edatagrid("saveRow");
                //或取表中的所有行
                var rows=$("#calculateOtherChargesZtTable").edatagrid("getRows");
                // 单价：
                var otherChargesPrice=0;
                rows.forEach(function (val) {
                    otherChargesPrice =otherChargesPrice+Number(val.otherChargesPrice);
                })
                //往赋值
                $("#other_charges").numberbox("setValue",otherChargesPrice);
                //保存到临时全局变量中
                calculateOtherChargesZtTableData=rows;
                //关闭窗口
                $("#calculateOtherChargesZtDialog").dialog("close");

            }
        }],
        onClose:function () {
            //销毁弹窗内容
            $("#calculateOtherChargesZtDialog").dialog("destroy")
        }

    })
}
//计算单价
function calculateOtherChargesZtTableonChange(){
    //获取指定行的编辑器
    var editor=$("#calculateOtherChargesZtTable").datagrid("getEditors",getRowIndex(this));
    var otherChargesMoney=$(editor[1].target).numberbox("getValue"); //金额
    var otherChargesNum=$(editor[2].target).numberbox("getValue");  //数量
    var otherChargesPrice=$(editor[3].target)//单价
    if (!otherChargesNum || otherChargesNum==0){  //除数不能为0，不能undefined
        otherChargesPrice.numberbox("setValue",0)
    }else {
        otherChargesPrice.numberbox("setValue",Number(otherChargesMoney)/Number(otherChargesNum))
    }

}

//C 配件 ---------------------------------------------------start-----------------------------
//清空方法
function emptyMountings() {
    //纸箱全局变量变为空数组
    cartonTableData=[]
    cartonTableDataK=[]
    //在插入c配件表格先进行判断是否有数据，有则先删除后插入
    var cRows= costReportC.datagrid("getRows");
    if (cRows.length>0){
        costReportC.datagrid("loadData", {total: 0, rows: []})
        costReportC.datagrid('reloadFooter', [
            {
                mountings: 'Total of Part C:',
                mountingsPrice: 0,
            }
        ]);
    }
}

//添加纸箱方法
function addTarton(){
    //动态添加--不会造成页面 沉与
    $("#cost_report_c_tb").append('<div id="addTartonId" style="text-align: center" data-options="title:\'纸箱\'"></div>');
    $("#addTartonId").dialog({
        href: "/costReportForm/otherCost/tartonCost.html",
        width: 750,
        height: 350,
        border:true,
        collapsible:false,
        minimizable:false,
        maximizable:false,
        modal:true,
        onClose: function () {
            //关闭后销毁掉
            $("#addTartonId").dialog("destroy")
        },buttons: [{
            text:'添加',
            iconCls:'icon-add',
            handler:function(){
                var bool=true;
                $("#addTartonTable").edatagrid('saveRow')
                var rows=$('#addTartonTable').datagrid("getRows");
                var rowsc=$("#cost_report_c").edatagrid('getRows');

                if (rows.length>0){
                    $("#cost_report_c").edatagrid('saveRow')

                    rows.forEach(function (value,index) {
                        //封装随机数
                        value.randomNum=Date.parse(new Date())
                         //判断不能为空
                        if (!value.len ||!value.w ||!value.h ||!value.price ||!value.price1){
                            bool=false;
                            layer.msg("此项添加失败，必填项不能为空！");
                            return
                        }

                        //获取名称和价格
                        $("#cost_report_c").edatagrid('addRow', {
                            row: {
                                mountings: value.name,
                                mountingsPrice: value.price1,
                                type:value.t,
                                randomNum:value.randomNum
                            }
                        })
                        //保存到全局变量中
                        if (value.t==1){
                            cartonTableData.push(value);
                        }else {
                            cartonTableDataK.push(value);
                        }
                    })

                    if (bool) {
                        $('#addTartonTable').edatagrid('loadData',[]);
                        $("#cost_report_c").edatagrid('saveRow')
                        $("#addTartonId").dialog('close');
                    }
                }else {
                    layer.msg("添加失败，没有数据！");
                }
            }
        }],
        onLoad: function () {//加载完远程内容后触发
            //获取用户选中数据
            cutAddTartonTableType()
        }
    })
}

//系统配件方法
function systemMountings() {
    //动态添加--不会造成页面 沉与
    $("#cost_report_c_tb").append('<div id="systemMountingsdd" data-options="title:\'系统配件\'"></div>');
    $("#systemMountingsdd").dialog({
        href: "/costReportForm/mountings.html",
        width: 500,
        height: 550,
        onClose: function () {
            //关闭后销毁掉
            $("#systemMountingsdd").dialog("destroy")
        },
        onLoad: function () {//加载完远程内容后触发
            $("#systemMountingsTable").datagrid({//双击事件
                onDblClickRow: function (index, row) {
                    $("#cost_report_c").edatagrid('saveRow')
                    $("#cost_report_c").edatagrid('addRow', {
                        index: 0,
                        row: {
                            mountings: row.NAME,
                            mountingsPrice: row.CNYNNETPRICE
                        }
                    })
                    $("#cost_report_c").edatagrid('saveRow')
                    layer.msg("添加成功")
                    //关闭窗口
                    //$("#systemMountingsdd").dialog("close")

                }
            })
        }
    })

}

//税率 3%和13%触发事件
$('#v_a_t_export_tax_rate').numberbox({
    onChange: function () {
        //防止有时候A 水料价和C 其它两个表格：用户会忘记保存操作：这里进行保存操作下
        costReportA.edatagrid('saveRow');
        costReportC.edatagrid('saveRow');
        final_result();
    }
})
$('#tax_item_rate').numberbox({
    onChange: function () {
        final_result();
    }
})
$('#accessories_loss_rate').numberbox({
    onChange: function () {
        final_result();
    }
})
$('#quoted_price_man_hour').numberbox({
    onChange: function () {
        final_result();
    }
})

$('#customs_fee').numberbox({
    onChange: function () {
        other_expenses_count();
    }
});
$('#freight').numberbox({
    onChange: function (newValue) {
        $('#customsFeeCostOnChange').numberbox('setValue',newValue)
        other_expenses_count();
    }
});
$('#other_charges').numberbox({
    onChange: function () {
        other_expenses_count();
    }
});
$('#other_charges_total').numberbox({
    onChange: function () {
        other_labour();
    }
})

//实际报价
$('#reality_quoted_price').numberbox({
    onChange: function (newValue, oldValue) {
        if (newValue || newValue == 0.0000) {
            $("#costCurrency_type").combobox('readonly', false);
        } else {
            $("#costCurrency_type").combobox('readonly', true);
        }

        //计算【兑换后的金额】
        var cr = $('#conversion_rate').numberbox("getValue");
        if (cr) {
            $('#conversionMoney').numberbox("setValue", newValue / Number(cr));
        }

        //计算外销单 实际报价*0.63（0.92）/港币汇率    香港接单惠州做货：0.63,其它全是0.92
        var cfs = costReportFormSalesPkOrg.combobox("getValue");  //销售组织
        var cfoa = costReportFormPkOrgAccount.combobox("getValue");   //公司账套
        if (cfs == "0001O110000000001HC5" || cfs == "0001O110000000001HHM") {
            var val = commonAjax('get', '/costReportForm/getHKDRate', {"code": "HKD"})
            //公司账套：选择的数据获取获取表格数据   0001O110000000001HET澳宝化妆品（惠州）有限公司  0001O110000000001HGC兆婷
            var arrayData = [];
            var HKD_c = val[0].RATE;
            if (cfs == "0001O110000000001HC5" && cfoa == "0001O110000000001HET") {
                arrayData = [{
                    "exportSales": "香港接单惠州做货：",
                    "HKD_conversion": HKD_c,
                    "HKD_conversion_price": (newValue * 0.63 / Number(HKD_c)).toFixed(4)
                }];
            } else if (cfs == "0001O110000000001HC5" && cfoa == "0001O110000000001HGC") {
                arrayData = [{
                    "exportSales": "香港接单兆婷做货：",
                    "HKD_conversion": HKD_c,
                    "HKD_conversion_price": (newValue * 0.92 / Number(HKD_c)).toFixed(4)
                }];
            } else if (cfs == "0001O110000000001HHM" && cfoa == "0001O110000000001HET") {
                arrayData = [{
                    "exportSales": "国际接单惠州做货：",
                    "HKD_conversion": HKD_c,
                    "HKD_conversion_price": (newValue * 0.92 / Number(HKD_c)).toFixed(4)
                }];
            } else if (cfs == "0001O110000000001HHM" && cfoa == "0001O110000000001HGC") {
                arrayData = [{
                    "exportSales": "国际接单兆婷做货：",
                    "HKD_conversion": HKD_c,
                    "HKD_conversion_price": (newValue * 0.92 / Number(HKD_c)).toFixed(4)
                }];
            }
            $('#costExportales').datagrid("loadData", arrayData);
        }
        //计算实际报价除以1.13后价格
        $("#reality_quoted_price2").numberbox("setValue",newValue/1.13)
        //整套毛利
        final_result();
    }
})

//其他费用合共
function other_expenses_count() {
    var count = 0;
    var fumigation_charge = $("#fumigation_charge").numberbox('getValue');
    var carton_certificate = $("#carton_certificate").numberbox('getValue');
    var customs_fee = $("#customs_fee").numberbox('getValue');
    var freight = $("#freight").numberbox('getValue');
    var other_charges = $("#other_charges").numberbox('getValue');
    count = parseFloat(fumigation_charge) + parseFloat(carton_certificate) + parseFloat(customs_fee) + parseFloat(freight) + parseFloat(other_charges);
    $('#other_charges_total').numberbox('setValue', (count + 0.0001).toFixed(3));
}

//B人工成本+其他费用
function other_labour() {
    var count = 0;
    var rows = costReportB.datagrid('getFooterRows');
    var other_charges_total = $('#other_charges_total').numberbox('getValue');
    if (rows != undefined) {
        count = parseFloat(other_charges_total) + parseFloat(rows[0].price);
    } else {
        count = parseFloat(other_charges_total)
    }
    $('#totalOfPartB').numberbox('setValue', (count + 0.0001).toFixed(3));
    final_result();
}

//税款 总成本  实际报价
function final_result() {
    var a = costReportA.datagrid('getFooterRows'); //返回页脚行。
    var total_of_part_a = 0;                                            //A水料成本价 总计
    var b = costReportB.datagrid('getFooterRows');
    var man_hour_total = 0;                                             //人工工时总和
    var totalOfPartB = $('#totalOfPartB').numberbox('getValue');        //B 人工成本+其他费用 总和
    var c = costReportC.datagrid('getFooterRows');
    var mountingsPrice = 0;                                             //配件费合计
    var reality_quoted_price = parseFloat($('#reality_quoted_price').numberbox('getValue'));//实际报价
    var v_a_t_export_tax_rate = parseFloat($('#v_a_t_export_tax_rate').numberbox('getValue'));//增值/出口税率
    var tax_item_rate = parseFloat($('#tax_item_rate').numberbox('getValue'));//城建、教育税率
    var accessories_loss_rate = parseFloat($('#accessories_loss_rate').numberbox('getValue'));//配件耗损率
    var other_charges_total = parseFloat($('#other_charges_total').numberbox('getValue'));//其他费用合共
    var v_a_t_export_tax_cost = 0; //增值/出口税款
    var tax_item__cost = 0;//税款：[城建、教育税]
    var total_cost = 0;//总成本
    var total_cost_includes_tax = 0;//总成本含税
    var grossMarginMoney = 0;//整套毛利$

    //处理 A水料价的默认值   ：成本价总和   与  报价基准总和
    if (a != undefined) {
        total_of_part_a = parseFloat(a[0].costPrice);
    } else {
        total_of_part_a = 0;
    }

    //处理 B人工工时总和默认值
    if (b != undefined) {
        man_hour_total = parseFloat(b[0].pieceTime);
    } else {
        man_hour_total = 0;
    }

    if (c != undefined) {
        mountingsPrice = parseFloat(c[0].mountingsPrice);                   //配件费
    } else {
        mountingsPrice = 0;
    }

    //T2税款：计算方式：[F-(A+C)]X税率 = [实际报价-（水料成本价+配件费）]*手输入(内销：13%，外销：4%)
    v_a_t_export_tax_cost = (reality_quoted_price - (total_of_part_a + mountingsPrice)) * v_a_t_export_tax_rate / 100
    //$('#v_a_t_export_tax_cost').numberbox('setValue', (v_a_t_export_tax_cost + 0.0001).toFixed(3));
    $('#v_a_t_export_tax_cost').numberbox('setValue', v_a_t_export_tax_cost);

    //T3税款：计算方式：T2*12%(固定值)
    tax_item__cost = v_a_t_export_tax_cost * tax_item_rate / 100;
    $('#tax_item__cost').numberbox('setValue', (tax_item__cost + 0.0001).toFixed(3));

    //总成本：计算方式：A+B+C*(1.05~1.1) = 水料价+人工+其他费用+配件费*(配件损耗率)
    total_cost = parseFloat(total_of_part_a) + parseFloat(totalOfPartB) + parseFloat(mountingsPrice) * accessories_loss_rate;
    $('#total_cost').numberbox('setValue', (total_cost + 0.0001).toFixed(3));

    //含税总成本：计算方式：D+T2+T3  = T2税款+T3税款+总成本
    total_cost_includes_tax = (v_a_t_export_tax_cost + tax_item__cost + total_cost)
    $('#total_cost_includes_tax').numberbox('setValue', (total_cost_includes_tax + 0.0001).toFixed(3));

    //整套毛利￥
    grossMarginMoney = reality_quoted_price - total_cost_includes_tax;
    $('#grossMarginMoney').numberbox('setValue', (grossMarginMoney + 0.0001).toFixed(4));

    //整套毛利%
    $('#grossMarginRate').numberbox('setValue', (grossMarginMoney / reality_quoted_price * 100 + 0.0001).toFixed(2));
}

//格式化人工
function changeWorkerTypeNname(value) {

    if (value == 1) {
        return "配制人工"
    } else if (value == 2) {
        return "灌装基础人工"
    } else if (value == 3) {
        return "灌装/组装人工"
    } else if (value == 4) {
        return "搬运人工"
    }
    return value

}

//日期默认为当天
$("#costReportDate").val(new Date())

$("#costCurrency_type").combobox({
    valueField: "CODE",
    textField: "CODE",
    panelHeight: 130,
    data:[{"CODE":"RMB","RATE":"1","NAME":"人名币"},{"CODE":"AUD","RATE":4.5468,"RATEDATE":"2020-05-06","NAME":"澳大利亚元"},{"CODE":"EUR","RATE":7.6592,"RATEDATE":"2020-05-06","NAME":"欧元"},{"CODE":"HKD","RATE":0.91178,"RATEDATE":"2020-05-06","NAME":"港币"},{"CODE":"GBP","RATE":8.7937,"RATEDATE":"2020-05-06","NAME":"英镑"},{"CODE":"JPY","RATE":0.0664,"RATEDATE":"2020-05-06","NAME":"日元"},{"CODE":"USD","RATE":7.069,"RATEDATE":"2020-05-06","NAME":"美元"}],
})

//兑换后金额
$("#conversionMoney").numberbox({
    onChange:function (newValue,oldValue) {
        //兑换率
        var conversionRate =$("#conversion_rate").numberbox("getValue");
        if(!conversionRate || conversionRate==0.0000){
            $("#conversion_rate").numberbox("setValue",1);
            conversionRate=1;
        }
        $("#reality_quoted_price").numberbox("setValue",(conversionRate*newValue).toFixed(4))
    }
})


$("#conversion_rate").numberbox({
    onChange:function (newValue,oldValue) {
        //除数不能为0
        if(!newValue || newValue==0.0000){
            $("#conversion_rate").numberbox("setValue",1);
            newValue=1;
        }

        //实际报价不能为Undefined
        var realityQuotedPrice =$("#reality_quoted_price").numberbox("getValue");
        if(!realityQuotedPrice){
            $("#reality_quoted_price").numberbox("setValue",0);
            newValue=0;
        }

        $("#conversionMoney").numberbox("setValue", (Number(realityQuotedPrice) / Number(newValue)).toFixed(4))
    }
})

